package com.kaibai.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class FileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 先判断数据是否为多端数据
        if(ServletFileUpload.isMultipartContent(request)){
            //创建FileItemFactory实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析数据的工具类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try{
                // 解析数据，得到表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);
                // 循环判断每一个表单项，是普通还是文件
                for(FileItem fileItem : list){
                    if(fileItem.isFormField()){
                        // 普通表单项
                    }else{
                        if(fileItem.getName().endsWith(".jpg")){
                            fileItem.write(new File("C:\\Users\\冲塔怪\\IdeaProjects\\27-bighomework\\src\\main\\webapp\\img\\"+fileItem.getName()));
                            response.sendRedirect(request.getHeader("Referer"));
                        }

                        // 文件
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }

        }
    }


}
